import json
from datetime import datetime

from django.forms import model_to_dict
from django.http import JsonResponse
from django.shortcuts import render
from django.template.defaultfilters import title
from django.views.decorators.csrf import csrf_exempt

from lianxi20250922.models import category, Fu


# Create your views here.
@csrf_exempt
def add_category(request):
    data=json.loads(request.body)
    if data['price']<=0:
        return JsonResponse(
            {
                'msg':'价格需要为正数'
            }
        )
    if category.objects.filter(id=data['category']).exists() is False:
        return JsonResponse(
            {
                'msg':'请输入有效的分类'
            }
        )
    a=Fu.objects.create(
        title=data['title'],
        price=data['price'],
        publish_date=datetime.now(),
        category_id=data['category']
    )
    return JsonResponse(
        {
            'msg':'添加成功',
            'item':model_to_dict(a)
        }
    )
def del_category(request):
    data=json.loads(request.body)
    if data['category_id']=='':
        return JsonResponse(
            {
                'msg':'参数必填'
            }
        )
    s=Fu.objects.filter(category_id=data['category_id'])
    for i in s:
        if i.id != '':
            return JsonResponse(
                {
                    'msg': '该类目下有服装'
                }
            )
    category.objects.get(id=data['category_id']).delete()
    return JsonResponse(
        {
            'msg':'删除成功'
        }
    )
@csrf_exempt
def del_fu(request):
    data=json.loads(request.body)
    if data['id']=='':
        return JsonResponse(
            {
                'msg':'id必填'
            }
        )
    if Fu.objects.filter(id=data['id']).exists() is False:
        return JsonResponse(
            {
                'msg':'id必填'
            }
        )
    Fu.objects.get(id=data['id']).delete()
@csrf_exempt
def update_category(request):
    data=json.loads(request.body)
    if data['title']=='':
        return JsonResponse(
            {
                'msg':'参数必填'
            }
        )
    if Fu.objects.filter(title=data['title']).exists() is False:
        return JsonResponse(
            {
                'msg':'请输入拥有的服装'
            }
        )
    item=Fu.objects.filter(title=data['title'])
    l=[]
    for i in item:
        i.category_id=data['category']
        i.save()
        l.append(
            {
                'id':i.id,
                "title": i.title,
                "price": i.price,
                "category": i.category_id
            }
        )
    return JsonResponse(
        {
            'msg':'修改成功',
            'item':l
        }
    )